package com.foxmail.aroundme.boring.base.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

import com.foxmail.aroundme.boring.BuildConfig;
import com.foxmail.aroundme.boring.R;
import com.foxmail.aroundme.boring.annotation.ActivityFragmentInject;
import com.foxmail.aroundme.boring.app.App;
import com.foxmail.aroundme.boring.base.present.BasePre;
import com.foxmail.aroundme.boring.base.view.BaseView;
import com.foxmail.aroundme.boring.manager.SettingManager;
import com.foxmail.aroundme.boring.utils.util.ViewUtil;
import com.foxmail.aroundme.boring.weight.header.Header;
import com.socks.library.KLog;
import com.squareup.leakcanary.RefWatcher;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import rx.Observable;

/**
 * Created by gzl on 1/14/17.
 *
 */

public abstract class BaseActivity<T extends BasePre> extends AppCompatActivity implements View.OnClickListener, BaseView {

    /**
     * 抽取代理类通用行为
     */
    protected T mPresenter;

    /**
     * 布局ID
     */
    protected int mContentViewId;

    /**
     * 是否存在NavigationView
     */
    protected boolean mHasNavigationView;

    /**
     * 滑动布局
     */
    protected DrawerLayout mDrawerLayout;

    /**
     * 获取tittleBar
     */
    protected Header mHeader;

    /**
     * Toolbar左侧按钮的样式
     */
    private int mLeftButtonId;

    /**
     * 结束Activity的可观测对象
     */
    private Observable<Boolean> mFinishObservable;


    /**
     * 是否存在titleBar
     */
    private boolean isTitleBar;

    /**
     * 右边button
     */
    private int mRigthButtonId;

    /**
     * 右边button
     */
    private int mTwoRigthButtonId;

    /**
     * 标题
     */
    private int mTitle;

    /**
     * logo
     */
    private int mLogo;

    /**
     * 是否全屏
     */
    private boolean isFullScreen;

    /**
     * 是否存在搜索
     */
    private boolean isShowSearch;

    /**
     * 是否滑屏退出
     */
    private boolean isSlideOut;

    private float startX = 0;
    private float startY = 0;
    private final float offsetX = SettingManager.getInstance().getW(App.getContext());
    private final float offsetY = SettingManager.getInstance().getH(App.getContext());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getClass().isAnnotationPresent(ActivityFragmentInject.class)) {
            ActivityFragmentInject annotation = getClass().getAnnotation(ActivityFragmentInject.class);
            mContentViewId = annotation.contentViewId();
            mHasNavigationView = annotation.hasNavigationView();
            isTitleBar = annotation.hasTitleBar();
            mLeftButtonId = annotation.leftButtonId();
            mRigthButtonId = annotation.rightButtonId();
            mTwoRigthButtonId = annotation.rightTwoButtonId();
            mTitle = annotation.barTitle();
            mLogo = annotation.logo();
            isFullScreen = annotation.fullScreen();
            isShowSearch = annotation.showSearch();
            isSlideOut = annotation.slideOut();
        } else {
            initView();
            initIntentData();
            initListener();
            return;
        }

        if (isFullScreen) {
            ViewUtil.setFullScreen(this);
        }

        setContentView(mContentViewId);

        if (isTitleBar) {
            mHeader = Header.create(this, R.id.main_title)
                    .setLeftButton(mLeftButtonId, this)
                    .setRightButton(mRigthButtonId, this)
                    .setLogo(mLogo).setTitle(mTitle)
                    .setTwoRightButton(mTwoRigthButtonId, this);
        }

        if (mHasNavigationView) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            }
            initNavigationView();
        }
        initView();
        initIntentData();
        initListener();
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPresenter != null) {
            mPresenter.onResume();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
    }

    private void initNavigationView() {

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            // 为4.4透明状态栏布局延伸到状态栏做适配
            mDrawerLayout.setFitsSystemWindows(false);
        }

        mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                SettingManager.getInstance().setIsMenuShow(true);
                if (BuildConfig.DEBUG) {
                    KLog.i("菜单开启");
                }
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                SettingManager.getInstance().setIsMenuShow(false);
                if (BuildConfig.DEBUG) {
                    KLog.i("菜单关闭");
                }
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        findViewById(R.id.channel).setOnClickListener(this);
        findViewById(R.id.interest).setOnClickListener(this);
        findViewById(R.id.favorite).setOnClickListener(this);
        findViewById(R.id.feedback).setOnClickListener(this);
        findViewById(R.id.setting).setOnClickListener(this);
        findViewById(R.id.notification).setOnClickListener(this);

    }
    public void showActivity(Intent it) {
        ActivityCompat.startActivity(this, it, null);
    }

    public void showActivity(Intent it, int requestCode) {
        ActivityCompat.startActivityForResult(this, it, requestCode, null);
    }


    /**
     * 执行转场动画
     *
     * @param v view
     * @param it intent
     */
    public void showActivityScaleUp(View v, Intent it) {
        if (v != null) {
            ActivityOptionsCompat options = ActivityOptionsCompat
                    .makeScaleUpAnimation(v, v.getWidth() / 2, v.getHeight() / 2, 0, 0);
            ActivityCompat.startActivity(this, it, options.toBundle());
        } else {
            ActivityCompat.startActivity(this, it, null);
        }
    }

    /**
     * 执行转场动画
     *
     * @param v view
     * @param it intent
     * @param requestCode return code
     */
    public void showActivityScaleUp(View v, Intent it, int requestCode) {
        if (v != null) {
            ActivityOptionsCompat options = ActivityOptionsCompat
                    .makeScaleUpAnimation(v, v.getWidth() / 2, v.getHeight() / 2, 0, 0);
            ActivityCompat.startActivityForResult(this, it, requestCode, options.toBundle());
        } else {
            ActivityCompat.startActivityForResult(this, it, requestCode, null);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
                // 返回键时未关闭侧栏时关闭侧栏
                mDrawerLayout.closeDrawer(Gravity.LEFT);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /*
     * 側滑返回
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!isSlideOut) {
            return super.dispatchTouchEvent(ev);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = ev.getX();
                startY = ev.getY();
                break;

            case MotionEvent.ACTION_MOVE:
                if (Math.abs(ev.getY() - startY) > (offsetY / 8)) {
                    startX = 0;
                    startY = 0;
                    return super.dispatchTouchEvent(ev);
                }
                break;

            case MotionEvent.ACTION_UP:
                if (startX == 0 && startY == 0) {
                    return super.dispatchTouchEvent(ev);
                }
                //X轴大于1/3 Y轴小于于１/8
                if ((ev.getX() - startX) > offsetX / 3
                        && (Math.abs(ev.getY() - startY) < (offsetY / 8))) {
                    onBackPressed();
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_icon:
                break;
            case R.id.leftButton:
            case R.id.left:
                if (mHasNavigationView) {
                    showMenu();
                } else {
                    onBackPressed();
                }
                break;
            case R.id.channel:
                closeMenu();
                break;
            case R.id.interest:
                closeMenu();
                break;
            case R.id.favorite:
                closeMenu();
                break;
            case R.id.feedback:
                closeMenu();
                break;
            case R.id.setting:
                closeMenu();
                break;
            case R.id.notification:
                closeMenu();
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showMenu() {
        if (!mHasNavigationView) {
            return;
        }
        if (mDrawerLayout == null) {
            return;
        }
        if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
            mDrawerLayout.closeDrawer(Gravity.LEFT);

        } else {
            mDrawerLayout.openDrawer(Gravity.LEFT);
        }
    }

    private void closeMenu() {
        if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
            mDrawerLayout.closeDrawer(Gravity.LEFT);

        }
    }
    //Dismiss dialog
    public void dismissDialog(String tag) {
        DialogFragment fragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(tag);
        if (fragment == null) {
            return;
        }

        if (fragment.isDetached() || fragment.isHidden()) {
            return;
        }

        try {
            fragment.dismissAllowingStateLoss();
        } catch (IllegalStateException e) {
            if (BuildConfig.DEBUG) {
                KLog.e("dialog取消错误=" + e);
            }
        }

    }
    protected abstract void initView();

    protected abstract void initIntentData();

    protected abstract void initListener();

}

